# 需要有的已知数据：
# - 生成的预测矩阵：outputs
# - 数据集名称：name (比如IP、SA、PU)

import numpy as np
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix, cohen_kappa_score
from operator import truediv

# AA_andEachClassAccuracy 函数
def AA_andEachClassAccuracy(confusion_matrix):
    list_diag = np.diag(confusion_matrix)
    list_raw_sum = np.sum(confusion_matrix, axis=1)
    each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum))
    average_acc = np.mean(each_acc)
    return each_acc, average_acc

# 生成准确率报告的函数
def generate_accuracy_report(y_test, y_pred, target_names):
    classification = classification_report(y_test, y_pred, target_names=target_names, digits=4)
    oa = accuracy_score(y_test, y_pred)
    confusion = confusion_matrix(y_test, y_pred)
    each_acc, aa = AA_andEachClassAccuracy(confusion)
    kappa = cohen_kappa_score(y_test, y_pred)

    return classification, confusion, oa * 100, each_acc * 100, aa * 100, kappa * 100


# 已经得到了outputs作为预测结果，y_test是实际标签
# 过滤掉标签为 0 的数据
valid_mask = y != 0
y_test = y.flatten()[valid_mask.flatten()]  # 展平后的真实标签
y_pred = outputs.flatten()[valid_mask.flatten()]  # 展平后的预测结果

# 根据数据集名称选择目标标签
if name == 'IP':
    target_names = ['Alfalfa', 'Corn-notill', 'Corn-mintill', 'Corn'
        , 'Grass-pasture', 'Grass-trees', 'Grass-pasture-mowed',
                    'Hay-windrowed', 'Oats', 'Soybean-notill', 'Soybean-mintill',
                    'Soybean-clean', 'Wheat', 'Woods', 'Buildings-Grass-Trees-Drives',
                    'Stone-Steel-Towers']
elif name == 'SA':
    target_names = ['Brocoli_green_weeds_1', 'Brocoli_green_weeds_2', 'Fallow', 'Fallow_rough_plow', 'Fallow_smooth',
                    'Stubble', 'Celery', 'Grapes_untrained', 'Soil_vinyard_develop', 'Corn_senesced_green_weeds',
                    'Lettuce_romaine_4wk', 'Lettuce_romaine_5wk', 'Lettuce_romaine_6wk', 'Lettuce_romaine_7wk',
                    'Vinyard_untrained', 'Vinyard_vertical_trellis']
elif name == 'PU':
    target_names = ['Asphalt', 'Meadows', 'Gravel', 'Trees', 'Painted metal sheets', 'Bare Soil', 'Bitumen',
                    'Self-Blocking Bricks', 'Shadows']


# 生成准确率报告
classification, confusion, oa, each_acc, aa, kappa = generate_accuracy_report(y_test, y_pred, target_names)

import datetime

# 获取当前时间的时间戳
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

# 使用时间戳创建文件名
file_name = f"classification_report_{timestamp}.txt"

with open(file_name, 'w') as x_file:
    x_file.write("Classification Report:\n")
    x_file.write(classification)
    x_file.write("\n")
    x_file.write(f"Overall Accuracy: {oa:.2f}%\n")
    x_file.write(f"Average Accuracy: {aa:.2f}%\n")
    x_file.write(f"Kappa Score: {kappa:.2f}\n\n")
    x_file.write("Confusion Matrix:\n")
    for row in confusion:
        x_file.write("\t")
        x_file.write("\t".join(map(str, row)) + "\n")
    x_file.write("\n")
    x_file.write(f"Each Class Accuracy:\n")
    for label, acc in zip(target_names, each_acc):
        x_file.write(f"{label.rjust(35 - 1)}: {acc:.4f}%\n")